package com.hemaapp.yjnh.activity;

import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.android.uu.view.HorizontalListView;
import com.hemaapp.hm_FrameWork.HemaNetTask;
import com.hemaapp.hm_FrameWork.result.HemaArrayResult;
import com.hemaapp.hm_FrameWork.result.HemaBaseResult;
import com.hemaapp.hm_FrameWork.result.HemaPageArrayResult;
import com.hemaapp.yjnh.BaseActivity;
import com.hemaapp.yjnh.BaseHttpInformation;
import com.hemaapp.yjnh.BaseUtil;
import com.hemaapp.yjnh.R;
import com.hemaapp.yjnh.adapter.CmnProductionAdapter;
import com.hemaapp.yjnh.bean.AdImage;
import com.hemaapp.yjnh.bean.Blog;
import com.hemaapp.yjnh.bean.BlogType;
import com.hemaapp.yjnh.bean.Nation;
import com.hemaapp.yjnh.bean.User;
import com.hemaapp.yjnh.listener.OnBlogItemClickListener;
import com.hemaapp.yjnh.view.ImageCarouselBanner;

import java.util.ArrayList;

import butterknife.Bind;
import butterknife.ButterKnife;
import xtom.frame.util.XtomToastUtil;
import xtom.frame.util.XtomWindowSize;
import xtom.frame.view.XtomListView;
import xtom.frame.view.XtomRefreshLoadmoreLayout;
import xtom.frame.view.XtomRefreshLoadmoreLayout.OnStartListener;

/**
 * 特产
 * @author GuiyouZhang
 */
public class SpecialtyActivity extends BaseActivity implements OnClickListener {

    private TextView titleText;
    private ImageButton titleLeft;
    private Button titleRight;
    private ImageView titleSearch;
    private XtomRefreshLoadmoreLayout layoutRefresh;
    private XtomListView listview;
    private LinearLayout ll_return_top;

    private View headerView;
    private ImageCarouselBanner imageCarouselBanner;
    private HorizontalListView listview_nation1;
    private ImageView iv_more;
    private ListView listview_vertical;

    private User user;
    private int page;
    private ArrayList<AdImage> imgs = new ArrayList<AdImage>();
    private ArrayList<Blog> mBlogs = new ArrayList<Blog>();//推荐的地标商品
    private ArrayList<Nation> nations = new ArrayList<Nation>();//所有的名族
    private ArrayList<BlogType> blogTypes = new ArrayList<>();//商品分类
    private CmnProductionAdapter mAdapter;
    private Nation1Adapter adapter1;
    private Nation2Adapter adapter2;
    private PopupWindow mPopupWindow;
    private String nationName = "汉族";//选中的名族
    private String typeName = "";//商品分类

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_organic);
        user = getApplicationContext().getUser();
        super.onCreate(savedInstanceState);
        init();
    }

    @Override
    protected void findView() {
        titleText = (TextView) findViewById(R.id.title_text);
        titleLeft = (ImageButton) findViewById(R.id.title_left_btn);
        titleRight = (Button) findViewById(R.id.title_right_btn);
        titleSearch = (ImageView) findViewById(R.id.title_right_img);

        layoutRefresh = (XtomRefreshLoadmoreLayout) findViewById(R.id.refreshLoadmoreLayout);
        listview = (XtomListView)findViewById( R.id.listview );
        ll_return_top = (LinearLayout) findViewById(R.id.ll_return_top);//回到顶部
    }

    @Override
    protected void getExras() {
    }

    @Override
    protected void setListener() {
        titleLeft.setOnClickListener(this);
        titleText.setText("特产");
        titleRight.setVisibility(View.GONE);
        titleSearch.setVisibility(View.VISIBLE);
        titleSearch.setOnClickListener(this);
        layoutRefresh.setOnStartListener(new StartListener());
        ll_return_top.setOnClickListener(this);
    }

    private void init() {
        headerView = LayoutInflater.from(mContext).inflate(R.layout.header_specialty, null);
        findHeaderViews();
        listview.addHeaderView(headerView);
        getNetWorker().getNationList();//获取名族列表
        getNetWorker().getBlogTypeList("6", "0");//商品分类
    }

    private void findHeaderViews() {
        imageCarouselBanner = (ImageCarouselBanner) headerView.findViewById(R.id.image_carousel_banner);
        listview_nation1 = (HorizontalListView) headerView.findViewById(R.id.listview_nation1);
        iv_more = (ImageView) headerView.findViewById(R.id.iv_more);
        iv_more.setOnClickListener(this);
    }
    /**
     * 获取图片列表
     */
    private void getImageList() {
        getNetWorker().ModelADList("3", "");
    }

    /**
     * 获取商品列表
     */
    private void getGoodsList() {
        if (nationName.equals("全部")) {
            nationName = "无";
        }
        if (typeName.equals("全部分类")) {
            typeName = "";
        }
        getNetWorker().blogList("11", nationName, "1", "1", "", "", "", "", "", "", "", "", "", typeName, page + "");
    }

    @Override
    protected void callBeforeDataBack(HemaNetTask netTask) {
        BaseHttpInformation information = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (information) {
            case MODELAD_LIST:
            case BLOG_LIST:
            case NATION_LIST:
            case BLOGTYPE_LIST:
                showProgressDialog("请稍候");
                break;
        }
    }

    @Override
    protected void callAfterDataBack(HemaNetTask netTask) {
        BaseHttpInformation information = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (information) {
            case MODELAD_LIST:
            case BLOG_LIST:
            case NATION_LIST:
            case BLOGTYPE_LIST:
                cancelProgressDialog();
                break;
        }
    }

    @Override
    protected void callBackForServerSuccess(HemaNetTask netTask,
                                            HemaBaseResult baseResult) {
        BaseHttpInformation information = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (information) {
            case NATION_LIST:
                HemaPageArrayResult<Nation> nResult = (HemaPageArrayResult<Nation>) baseResult;
                if (nResult == null || nResult.getObjects() == null)
                    return;
                if (nResult.getObjects().size() > 0) {
                    nations.clear();
                    Nation nation = new Nation();
                    nation.setName("全部");
                    nation.setChecked(true);
                    nations.add(nation);
                    nations.addAll(nResult.getObjects());
                    nationName = "全部";
                    layoutRefresh.getOnStartListener().onStartRefresh(layoutRefresh);
                    refreshNation1();
                }
                break;
            case BLOGTYPE_LIST:
                HemaArrayResult<BlogType> typeResult = (HemaArrayResult<BlogType>) baseResult;
                if (typeResult == null || typeResult.getObjects() == null)
                    return;
                blogTypes.clear();
                BlogType allType = new BlogType();
                allType.setName("全部分类");
                allType.setChecked(true);
                blogTypes.add(allType);
                blogTypes.addAll(typeResult.getObjects());
                break;
            case MODELAD_LIST://广告
                HemaPageArrayResult<AdImage> aResult = (HemaPageArrayResult<AdImage>) baseResult;
                if (aResult == null || aResult.getObjects() == null)
                    return;
                if (imgs == null) {
                    imgs = new ArrayList<AdImage>();
                } else {
                    imgs.clear();
                }
                imgs.addAll(aResult.getObjects());
                initADPager();
                break;
            case BLOG_LIST:
                HemaPageArrayResult<Blog> bResult = (HemaPageArrayResult<Blog>) baseResult;
                if (bResult == null || bResult.getObjects() == null)
                    return;
                if (page == 0) {// 刷新
                    layoutRefresh.refreshSuccess();
                    mBlogs.clear();
                    this.mBlogs.addAll(bResult.getObjects());
                } else {
                    layoutRefresh.loadmoreSuccess();
                    if (bResult.getObjects().size() > 0) {
                        this.mBlogs.addAll(bResult.getObjects());
                    } else {
                        layoutRefresh.setLoadmoreable(false);
                        XtomToastUtil.showShortToast(mContext, "已经到最后啦");
                    }
                }
                refreshDatas(-1);
                break;
        }
    }

    @Override
    protected void callBackForServerFailed(HemaNetTask netTask,
                                           HemaBaseResult baseResult) {
        BaseHttpInformation information = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (information) {
            case MODELAD_LIST:
            case BLOG_LIST:
                if (page == 0) {// 刷新
                    layoutRefresh.refreshFailed();
                } else {
                    layoutRefresh.loadmoreFailed();
                }
                XtomToastUtil.showShortToast(mContext, "获取商品信息失败，" + baseResult.getMsg());
                break;
            case NATION_LIST:
                XtomToastUtil.showShortToast(mContext, "获取民族信息失败，" + baseResult.getMsg());
                break;
            default:
                break;
        }
    }

    @Override
    protected void callBackForGetDataFailed(HemaNetTask netTask, int failedType) {
        BaseHttpInformation information = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (information) {
            case MODELAD_LIST:
            case BLOG_LIST:
                if (page == 0) {// 刷新
                    layoutRefresh.refreshFailed();
                } else {
                    layoutRefresh.loadmoreFailed();
                }
                XtomToastUtil.showShortToast(mContext, "获取商品信息失败，请稍后再试");
                break;
            case NATION_LIST:
                XtomToastUtil.showShortToast(mContext, "获取民族信息失败，请稍后再试");
                break;
            default:
                break;
        }
    }

    /**
     * 商品列表
     *
     * @param failedType
     */
    private void refreshDatas(int failedType) {
        if (mAdapter == null) {
            mAdapter = new CmnProductionAdapter(mContext, mBlogs);
            mAdapter.setItemClickListener(new OnBlogItemClickListener() {
                @Override
                public void onClickListener(int position) {
                    Intent it = new Intent(mContext, CmnProductionDetailActivity.class);
                    it.putExtra("blog_id", mBlogs.get(position).getId());
                    mContext.startActivity(it);
                }

                @Override
                public void onCartListener(int position) {

                }
            });
            mAdapter.setEmptyString("暂无商品");
            listview.setAdapter(mAdapter);
        }else {
            mAdapter.notifyDataSetChanged();
        }
        mAdapter.setFailtype(failedType);
    }

    /**
     * 刷新水平名族列表
     */
    private void refreshNation1() {
        if (adapter1 == null) {
            adapter1 = new Nation1Adapter();
            listview_nation1.setAdapter(adapter1);
        } else {
            adapter1.notifyDataSetChanged();
        }
    }

    /**
     * 刷新垂直名族列表
     */
    private void refreshNation2() {
        if (adapter2 == null) {
            adapter2 = new Nation2Adapter();
            listview_vertical.setAdapter(adapter2);
        } else {
            adapter2.notifyDataSetChanged();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.title_left_btn:
                finish();
                break;
            case R.id.title_right_img://进入搜索界面
                Intent itSearch = new Intent(mContext, SearchActivity.class);
                itSearch.putExtra("type", 11);
                itSearch.putExtra("assort", "特产");
                startActivity(itSearch);
                break;
            case R.id.ll_return_top:
                listview.setSelection(0);
                break;
            case R.id.iv_more:
                showVerticalNation();
                break;
            default:
                break;
        }
    }

    private class StartListener implements OnStartListener {

        @Override
        public void onStartRefresh(XtomRefreshLoadmoreLayout v) {
            page = 0;
            getImageList();
            getGoodsList();
        }

        @Override
        public void onStartLoadmore(XtomRefreshLoadmoreLayout v) {
            page++;
            getGoodsList();
        }
    }

    private void initADPager() {
        ArrayList<String> urls = new ArrayList<>();
        for (AdImage item : imgs) {
            urls.add(item.getImgurl());
        }
        imageCarouselBanner.getLayoutParams().height = XtomWindowSize.getWidth(mContext)/2;
        imageCarouselBanner.onInstance(mContext, urls, R.drawable.ad_show_indicator,
                new ImageCarouselHeadClickListener(mContext, imgs, "2"));
    }

    /**
     * 显示垂直民族列表
     */
    private void showVerticalNation() {
        if (mPopupWindow == null) {
            initPopuptWindow();
        }
        refreshNation2();
        mPopupWindow.showAsDropDown(iv_more);
    }

    private void initPopuptWindow() {
        final View popView = mContext.getLayoutInflater().inflate(R.layout.pop_specialty_nation, null);
        listview_vertical = (ListView) popView.findViewById(R.id.listView);

        mPopupWindow = new PopupWindow(popView, LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
        //设置SelectPicPopupWindow弹出窗体可点击
        mPopupWindow.setFocusable(true);
        mPopupWindow.setBackgroundDrawable(new BitmapDrawable());
        popView.setOnTouchListener(new OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                int top = listview_vertical.getTop();
                int wide = listview_vertical.getLeft();
                int bottom = listview_vertical.getBottom();
                int y = (int) event.getY();
                int x = (int) event.getX();
                if (x < wide || y < top || y > bottom) {
                    refreshNation1();
                    mPopupWindow.dismiss();
                }
                return true;
            }
        });
    }

    /**
     * 水平滚动的名族适配器
     *
     * @author GuiyouZhang
     *         Date：2015年12月21日 下午5:41:04
     *         Email:guiyouzhang@163.com
     */
    public class Nation1Adapter extends BaseAdapter {

        @Override
        public int getCount() {
            return nations.size();
        }

        @Override
        public Object getItem(int position) {
            // TODO Auto-generated method stub
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder;
            if (convertView == null || convertView.getTag(R.id.TAG_VIEWHOLDER) == null) {
                holder = new ViewHolder();
                convertView = LayoutInflater.from(mContext).inflate(R.layout.listitem_specialty_nation1, null);
                findHolderViews(convertView, holder);
                convertView.setTag(R.id.TAG_VIEWHOLDER, holder);
            } else {
                holder = (ViewHolder) convertView.getTag(R.id.TAG_VIEWHOLDER);
            }
            setData(position, holder);
            return convertView;
        }

        private class ViewHolder {
            private TextView tvNation;
            private ImageView ivLine;
        }

        private void findHolderViews(View convertView, ViewHolder holder) {
            holder.tvNation = (TextView) convertView.findViewById(R.id.tv_nation);
            holder.ivLine = (ImageView) convertView.findViewById(R.id.iv_line);
        }

        private void setData(final int position, ViewHolder holder) {
            final Nation nation = nations.get(position);
            holder.tvNation.setText("  " + nation.getName() + "  ");
            if (nation.isChecked()) {
                holder.tvNation.setTextColor(getResources().getColor(R.color.text_orange));
                holder.ivLine.setVisibility(View.VISIBLE);
            } else {
                holder.tvNation.setTextColor(getResources().getColor(R.color.text_black));
                holder.ivLine.setVisibility(View.INVISIBLE);
            }
            holder.tvNation.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    nationName = nation.getName();
                    layoutRefresh.getOnStartListener().onStartRefresh(layoutRefresh);
                    for (Nation nation1 : nations) {
                        nation1.setChecked(false);
                    }
                    nation.setChecked(true);
                    notifyDataSetChanged();
                }
            });
        }
    }

    /**
     * 垂直滚动的名族适配器
     *
     * @author GuiyouZhang
     *         Date：2015年12月21日 下午5:41:04
     *         Email:guiyouzhang@163.com
     */
    public class Nation2Adapter extends BaseAdapter {

        @Override
        public int getCount() {
            return blogTypes.size();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder;
            if (convertView == null || convertView.getTag(R.id.TAG_VIEWHOLDER) == null) {
                convertView = LayoutInflater.from(mContext).inflate(R.layout.item_specialty_type, null);
                holder = new ViewHolder(convertView);
                convertView.setTag(R.id.TAG_VIEWHOLDER, holder);
            } else {
                holder = (ViewHolder) convertView.getTag(R.id.TAG_VIEWHOLDER);
            }
            holder.setDatas(position);
            return convertView;
        }

        class ViewHolder {
            @Bind(R.id.iv_selector)
            ImageView ivSelector;
            @Bind(R.id.tv_type)
            TextView tvType;
            int position;

            ViewHolder(View view) {
                ButterKnife.bind(this, view);
                view.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        typeName = blogTypes.get(position).getName();
                        for (BlogType type : blogTypes)
                            type.setChecked(false);
                        blogTypes.get(position).setChecked(true);
                        layoutRefresh.getOnStartListener().onStartRefresh(layoutRefresh);
                        notifyDataSetChanged();
                        if (mPopupWindow.isShowing())
                            mPopupWindow.dismiss();
                    }
                });
            }

            public void setDatas(int position) {
                this.position = position;
                final BlogType blogType = blogTypes.get(position);
                tvType.setText(blogType.getName());
                if (blogType.isChecked()) {
                    tvType.setTextColor(getResources().getColor(R.color.theme_orange));
                    ivSelector.setVisibility(View.VISIBLE);
                } else {
                    tvType.setTextColor(getResources().getColor(R.color.text_black));
                    ivSelector.setVisibility(View.INVISIBLE);
                }
            }
        }
    }
}
